package tool

import (
	"power-bank/library/in"
	"strings"

	"github.com/go-xorm/xorm"
	"github.com/gogf/gf/net/ghttp"
)

//通用查询方法
//@r,
//@v ,*xorm.Engine或者*xorm.Session
func NewSession(r *ghttp.Request, v interface{}) *xorm.Session {
	index, size := in.GetPageSize(r)
	var session *xorm.Session

	switch db := v.(type) {
	case *xorm.Engine:
		session = db.Limit(size, index*size)
	case *xorm.Session:
		session = db.Limit(size, index*size)
	default:
		return nil
	}

	for i, v := range QueryMap(r) {
		switch i {
		case "asc", "Asc", "ASC":
			session.Asc(v[0])
		case "desc", "Desc", "DESC":
			session.Desc(v[0])
		case "index", "size":
		default:
			i = UpperFrist(i)
			if len(v) == 1 {
				if len(v[0]) > 4 && v[0][:4] == "like" {
					session.Where("`"+i+"` like ?", "%"+v[0][4:]+"%")
				} else {
					session.Where("`"+i+"`=?", v[0])
				}
			} else if len(v) > 1 {
				session.In(i, v)
			}
		}
	}
	return session
}

func UpperFrist(s string) string {
	if len(s) > 0 {
		return strings.ToUpper(string(s[0])) + s[1:]
	}
	return s
}

func QueryMap(r *ghttp.Request) map[string][]string {
	m := make(map[string][]string)
	for i, v := range r.URL.Query() {
		list := []string{}
		for _, s := range v {
			list = append(list, strings.Split(s, ",")...)
		}
		if len(list) > 0 {
			m[i] = list
		}
	}
	return m
}
